package com.shhic.hhplt.server.bkgrdui;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.shhic.hhplt.server.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.shhic.hhplt.server.model.CommonRtnValue;
import com.shhic.hhplt.server.model.NoPayload;
import com.shhic.hhplt.server.model.User;
import com.shhic.hhplt.server.model.UserRoleEnum;
import com.shhic.hhplt.server.util.EncryUtil;

@Controller
@RequestMapping("/framework/")
public class BackgroundLoginController {
	@Resource
	IUserService userService;

	/**
	 * 后台用户界面登录
	 * @param user	
	 * @return
	 */
	@PostMapping(value = "bkgrdLogin.do", produces = "text/json;charset=UTF-8")
	public ModelAndView bkgrdLogin(User user,HttpSession session){
		User existedUser = userService.getUser(user.getUsername(),EncryUtil.encry(user.getPassword()));
		if(existedUser == null){
			ModelAndView mv = new ModelAndView("forward:login.jsp");
			mv.addObject("message", "用户名或密码错误");
			return mv;
		}
		if(existedUser.getRole() != UserRoleEnum.MANAGER){
			ModelAndView mv = new ModelAndView("forward:login.jsp");
			mv.addObject("message", "用户权限不足，不能登录后台管理系统");
			return mv;
		}
		session.setAttribute("loginUser", user);
		return new ModelAndView("forward:index.jsp");
	}
	
	@RequestMapping(value = "bkgrdLogout.do", method = RequestMethod.GET,produces = "text/json;charset=UTF-8")
	public ModelAndView bkgrdLogout(User user,HttpSession session){
		session.removeAttribute("loginUser");
		ModelAndView mv = new ModelAndView("forward:login.jsp");
		mv.addObject("message", "您已登出");
		return mv;
	}
	
	
	@RequestMapping(value = "modifyPassword.do", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public CommonRtnValue<NoPayload> modifyPassword(@RequestParam String oldPassword,@RequestParam String newPassword,HttpSession session){
		User existedUser = (User)session.getAttribute("loginUser");
		CommonRtnValue<NoPayload> rtn = new CommonRtnValue<NoPayload>();
		if(existedUser == null){
			rtn.setRtnCode(-1);
			rtn.setMessage("用户未登录");
		}else if(!existedUser.getPassword().equals(oldPassword)){
			rtn.setRtnCode(-2);
			rtn.setMessage("原密码错误");
		}else{
			userService.updateUserPassword(existedUser.getUsername(),EncryUtil.encry(newPassword));
			existedUser.setPassword(newPassword);
			rtn.setRtnCode(0);
			rtn.setMessage("密码修改成功");
		}
		return rtn;
	}
	
	@RequestMapping(value = "heartbeat.do", method = RequestMethod.GET,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String heartbeat(){
		//心跳
		return "OK";
	}
}
